package com.sixseven.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sixseven.bean.*;
import com.sixseven.mapper.OrderItemMapper;
import com.sixseven.mapper.OrderMapper;
import com.sixseven.service.CowryService;
import com.sixseven.service.OrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * @author Belly
 * @version 1.1.0
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Resource
    private CowryService cowryService;
    @Resource
    private OrderItemMapper orderItemMapper;

    @Override
    public String saveOrder(Integer memberId, Cart cart) {
        if (cart == null){
            return null;
        }
        if (memberId == null){
            return null;
        }
        if (cart.getCartItemMap().size() == 0){
            return null;
        }
        //制作订单号
        String orderID = System.currentTimeMillis() + "" + memberId;
        //保存订单信息
        this.save(new Order(orderID, new Date(),
                cart.getFinalTotalPrice(), 0, memberId));
        //得到购物车里的商品
        Map<Integer, CartItem> cartItemMap = cart.getCartItemMap();
        //将购物车里的每一项添加到orderItem中
        for (Integer id : cartItemMap.keySet()) {
            CartItem cartItem = cartItemMap.get(id);
            //插入
            orderItemMapper.insert(new OrderItem(null, cartItem.getName(),
                    cartItem.getPrice(), cartItem.getCount(),
                    cartItem.getTotalPrice(), orderID));
            Cowry cowry = cowryService.getById(id);
            cowry.setSales(cowry.getSales() + cartItem.getCount());
            cowry.setStock(cowry.getStock() - cartItem.getCount());
            cowryService.updateById(cowry);
        }
        cartItemMap.clear();
        //返回订单号
        return orderID;
    }

}
